﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UL360SurveyCommon.Models;
using System.Xml.Linq;

namespace UL360SurveyCommon
{
    public static class Templating
    {
        /// <summary>
        /// Load an XML-mailtemplate with stream
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static List<GenericMailTemplate> LoadTemplate(System.IO.Stream s)
        {
            //Load XML-template file
            XElement root = XElement.Load(s);

            return LoadXML(root);
        }

        /// <summary>
        /// Load an XML-mailtemplate with path
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static List<GenericMailTemplate> LoadTemplate(string path)
        {
            //Load XML-template file
            XElement root = XElement.Load(path);

            return LoadXML(root);
        }

        private static List<GenericMailTemplate> LoadXML(XElement root)
        {
            //Create list of templates
            List<GenericMailTemplate> templates = new List<GenericMailTemplate>();

            //Loop through each language template
            foreach (XElement element in root.Descendants("language"))
            {
                //Get languageId
                int langId;
                int.TryParse(element.Attribute("id").Value, out langId);

                //Get if Message should be in HTML-format
                bool isHtml;
                bool.TryParse(element.Element("message").Attribute("isHtml").Value, out isHtml);

                //Add template to templatelist
                templates.Add(new GenericMailTemplate
                {
                    languageId = langId,
                    Subject = element.Element("subject").Value,
                    Message = element.Element("message").Value,
                    IsHtml = isHtml
                });
            }

            //Return all templates
            return templates;
        }
    }
}
